package com.qfmy.mystation.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.qfmy.mystation.R;
import com.qfmy.mystation.bean.Wallpaper;
import com.qfmy.mystation.databinding.FragmentMyWallpaperBinding;
import com.qfmy.mystation.dbHelper.WallpaperDBHelper;
import com.qfmy.mystation.ui.adapter.MyWallpaperAdapter;

import java.util.ArrayList;

public class MyWallpaperFragment extends Fragment {
    private FragmentMyWallpaperBinding binding;
    private int position = 0;
    private ArrayList<Wallpaper> wallpapers;

    public static MyWallpaperFragment newInstance() {
        return new MyWallpaperFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentMyWallpaperBinding.inflate(inflater, container, false);
        binding.rvWallpaper.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        binding.tbVp.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    wallpapers = WallpaperDBHelper.getAllCollectionWallpaper(requireContext());
                    binding.rvWallpaper.setAdapter(new MyWallpaperAdapter(requireContext(), wallpapers));
                    System.out.println(wallpapers);
                    System.out.println(tab.getText());
                } else if (tab.getPosition() == 1) {
                    wallpapers = WallpaperDBHelper.getAllDownloadWallpaper(requireContext());
                    binding.rvWallpaper.setAdapter(new MyWallpaperAdapter(requireContext(), wallpapers));
                    System.out.println(wallpapers);
                    System.out.println(tab.getText());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        binding.tbVp.addTab(binding.tbVp.newTab().setText(R.string.my_collection), true);
        binding.tbVp.addTab(binding.tbVp.newTab().setText(R.string.my_download));
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.tbVp.selectTab(binding.tbVp.getTabAt(position));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        position = binding.tbVp.getSelectedTabPosition();
        binding = null;
    }
}